import 'ol/ol.css';

import Map from "ol/Map";

import * as QinZhou from '@src/configs/GLOBAL_QinZhou.js';

import Icon from 'ol/style/Icon';
import Point from 'ol/geom/Point';
import Style from 'ol/style/Style';
import Fill from 'ol/style/Fill';
import Polygon from "ol/geom/Polygon";
import Feature from 'ol/Feature';
import MousePosition from 'ol/control/MousePosition';
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";

import initDevice from "@src/requests/qinzhou/InitDevice";

const diffX = -63801;
const diffY = 2697550;
const mapCoordTrans = (x, y) => [diffX - x / 1000, diffY - y / 1000];
const pointerPosition = { x: 0.0, y: 0.0, } // 记录鼠标当前的 EPSG:3857 坐标
const getScaleFactor = (currentZommLevel, baseZoomLevel) => Math.pow(2, currentZommLevel - baseZoomLevel); // ZoomLevel等比缩放函数

export const initialize = (id) => {

    // 初始化
    const { CENTER, MAP_DEFAULT_ZOOM, view } = QinZhou;
    const map = new Map({ target: id });

    // 锁定视角以及加载图层
    map.setView(view);
    map.addLayer(QinZhou.layer);
    const vectorLayer = new VectorLayer();
    const vectorSource = new VectorSource();
    vectorLayer.setSource(vectorSource);
    map.addLayer(vectorLayer);


    // EPSG:3857 坐标提示
    {
        const div3857 = document.createElement("div");
        document.body.appendChild(div3857);
        div3857.id = "mp-3857";
        const mp_3857 = new MousePosition({
            coordinateFormat: (event) => {
                pointerPosition.x = event[0];
                pointerPosition.y = event[1];
                return `EPSG:3857 (${event[0]}, ${event[1]})`;
            },
            projection: "EPSG:3857", // 和地图坐标系保持一致
            className: "custom-mouse-position", // css类名
            target: document.getElementById("mp-3857") // 显示位置鼠标坐标位置DOM
        });
        map.addControl(mp_3857);
        const div4326 = document.createElement("div");
        document.body.appendChild(div4326);
        div4326.id = "mp-4326";
        const mp_4326 = new MousePosition({
            coordinateFormat: (event) => {
                return `EPSG:4326 (${event[0]}, ${event[1]})`;
            },
            projection: "EPSG:4326", // 和地图坐标系保持一致
            className: "custom-mouse-position", // css类名
            target: document.getElementById("mp-4326") // 显示位置鼠标坐标位置DOM
        });
        map.addControl(mp_4326);
    }


    // 通过小车计算比例尺
    const ahtStatus = { scale: 0.1199 };
    const ahtPosition = [-64460.202683966956, 2697328.746852555];
    const aht = new Feature();
    aht.setId("aht-001")
    {
        aht.setGeometry(new Point(ahtPosition));
        const icon = new Icon({ src: "/aht.png", anchor: [0.0, 0.0], rotation: 0.0 }); // 这里anchor固定为左上角
        const style = new Style({ image: icon, zIndex: 0 });
        aht.setStyle(style);
        aht.updateScale = () => {
            const currentZommLevel = view.getZoom();
            const scaleRes = ahtStatus.scale * getScaleFactor(currentZommLevel, MAP_DEFAULT_ZOOM);
            icon.setScale(scaleRes);
            style.setImage(icon);
            aht.setStyle(style);
        };
        aht.updateScale();
        vectorSource.addFeature(aht);
        view.addEventListener("change:resolution", () => { aht.updateScale(); });
    }

    // 计算出来的属性
    const baseScale = 0.1199;
    const ratio1 = 15 / 184; // m/px ≈ 0.08152174
    const ratio2 = 184 / 15; // px/m ≈ 12.2666667
    const ahtTireGap = (42 - 36.8) / 2;

    /**
     * 用小车的比例来计算 其他地图物件的`初始化缩放比率`
     * @param targetImgPixelLength 这个物件的图片特征(* 长度/宽度或其他?)占据图片多少个像素
     * @param targetRealLength 这个物件的这个特征实际的长度占据多少m
     * @returns {number} targetBaseScale 这个物件的理论标准长度
     */
    const calculateTargetBaseScale = (targetImgPixelLength, targetRealLength) => {
        //                                  tragetRealLength
        //                             -------------------------
        //  targetBaseScale               targetImgPixelLength
        // ------------------- = ---------------------------------------
        //   ahtBaseScale                    ahtRealLength
        //                             ------------------------- = ratio1
        //                                  ahtImgPixelLength
        return (baseScale * targetRealLength) / (ratio1 * targetImgPixelLength);
    }

    // 岸桥
    const qcScale = calculateTargetBaseScale(1240, 124);
    const qcPositionY = 2697333.077569264;
    initDevice[1].data[0]['itemValue'].forEach(qcms => {
        const qcPositionX = mapCoordTrans(qcms["GantryPos"] * 10)[0];
        const qc = new Feature();
        const qcPosition = [qcPositionX, qcPositionY];
        qc.setGeometry(new Point(qcPosition));
        const icon = new Icon({ src: "/STS.png", anchor: [0.5, 1.0], rotation: 0.0, color: '#03A9F4' }); // 这里anchor固定为左上角
        const style = new Style({ image: icon, zIndex: 0 });
        qc.setStyle(style);
        qc.updateScale = () => {
            const currentZommLevel = view.getZoom();
            const scaleRes = qcScale * getScaleFactor(currentZommLevel, MAP_DEFAULT_ZOOM);
            icon.setScale(scaleRes);
            style.setImage(icon);
            qc.setStyle(style);
        };
        qc.updateScale();
        vectorSource.addFeature(qc);
        view.addEventListener("change:resolution", () => { qc.updateScale(); });
    });

    // 用 CONTAINER 集装箱 进行验证
    const containerFeature = new Feature();
    const calculateContainerCoords = () => {
        const centerX = ahtPosition[0] + 1.22 + 1.5 - 1.22 + (ahtTireGap) * ratio1;
        const centerY = ahtPosition[1] - 3.03;
        const containerXLength = 2.44; // 集装箱的宽度
        const containerYLength = 6.06; // 集装箱的长度
        const newCoordinates = [[
            [centerX - containerXLength / 2, centerY - containerYLength / 2],
            [centerX + containerXLength / 2, centerY - containerYLength / 2],
            [centerX + containerXLength / 2, centerY + containerYLength / 2],
            [centerX - containerXLength / 2, centerY + containerYLength / 2],
            [centerX - containerXLength / 2, centerY - containerYLength / 2]
        ]];
        return newCoordinates;
    };
    const containerPolygon = new Polygon(calculateContainerCoords());
    containerFeature.setGeometry(containerPolygon);
    containerFeature.setStyle(new Style({ fill: new Fill({ color: "#47EE1D" }), zIndex: 1 }));
    vectorSource.addFeature(containerFeature);
    containerFeature.getGeometry().update = () => {
        const currentZommLevel = view.getZoom();
        const scale = baseScale * getScaleFactor(currentZommLevel, MAP_DEFAULT_ZOOM);
        containerPolygon.setCoordinates(calculateContainerCoords(scale));
    }
    containerFeature.getGeometry().update();
    view.addEventListener("change:resolution", () => { containerFeature.getGeometry().update(); });

    // 计算/调试
    window.addEventListener("keydown", (e) => {
        if (e.code === "KeyS") {
            console.log("pointerPosition", pointerPosition);
            console.log("ahtStatus.scale", ahtStatus.scale);
        }
        else if (e.code === "ArrowUp") {
            ahtStatus.scale += 0.01;
            aht.updateScale();
        }
        else if (e.code === "ArrowDown") {
            ahtStatus.scale -= 0.01;
            aht.updateScale();
        }
    });

    // 再来些小车
    {
        const ahtScale = baseScale;
        const ahtPosition = [-64460.202683966956 + 6 + 3, 2697328.746852555 - 14];
        const aht = new Feature();
        aht.setGeometry(new Point(ahtPosition));
        const icon = new Icon({ src: "/aht.png", anchor: [0.5, 0.5], rotation: 0.0 }); // 这里anchor固定为中心点
        const style = new Style({ image: icon, zIndex: 0 });
        aht.setStyle(style);
        aht.updateScale = () => {
            const currentZommLevel = view.getZoom();
            const scaleRes = ahtScale * getScaleFactor(currentZommLevel, MAP_DEFAULT_ZOOM);
            icon.setScale(scaleRes);
            style.setImage(icon);
            aht.setStyle(style);
        };
        aht.updateScale();
        vectorSource.addFeature(aht);
        view.addEventListener("change:resolution", () => { aht.updateScale(); });
    }
    {
        const ahtScale = baseScale;
        const ahtPosition = [-64451.03552901758, 2697340.875417985 + (4.0 / 2.0)];
        const aht = new Feature();
        aht.setGeometry(new Point(ahtPosition));
        const icon = new Icon({ src: "/aht.png", anchor: [0.5, 0.5], rotation: Math.PI / 2.0 }); // 这里anchor固定为中心点
        const style = new Style({ image: icon, zIndex: 0 });
        aht.setStyle(style);
        aht.updateScale = () => {
            const currentZommLevel = view.getZoom();
            const scaleRes = ahtScale * getScaleFactor(currentZommLevel, MAP_DEFAULT_ZOOM);
            icon.setScale(scaleRes);
            style.setImage(icon);
            aht.setStyle(style);
        };
        aht.updateScale();
        vectorSource.addFeature(aht);
        view.addEventListener("change:resolution", () => { aht.updateScale(); });

        // 这辆车生成一个20长度的箱子
        const containerFeature = new Feature();
        const calculateContainerCoords = () => {
            const centerX = ahtPosition[0];
            const centerY = ahtPosition[1];
            const containerXLength = 2.44; // 集装箱的宽度
            const containerYLength = 6.06; // 集装箱的长度
            const newCoordinates = [[
                [centerX - containerXLength / 2, centerY - containerYLength / 2],
                [centerX + containerXLength / 2, centerY - containerYLength / 2],
                [centerX + containerXLength / 2, centerY + containerYLength / 2],
                [centerX - containerXLength / 2, centerY + containerYLength / 2],
                [centerX - containerXLength / 2, centerY - containerYLength / 2]
            ]];
            return newCoordinates;
        };
        const containerPolygon = new Polygon(calculateContainerCoords());
        containerFeature.setGeometry(containerPolygon);
        containerFeature.setStyle(new Style({ fill: new Fill({ color: "#47EE1D" }), zIndex: 1 }));
        vectorSource.addFeature(containerFeature);
        containerFeature.getGeometry().update = () => {
            const currentZommLevel = view.getZoom();
            const scale = baseScale * getScaleFactor(currentZommLevel, MAP_DEFAULT_ZOOM);
            containerPolygon.setCoordinates(calculateContainerCoords(scale));
            containerPolygon.rotate(-Math.PI / 2.0, ahtPosition);
        }
        containerFeature.getGeometry().update();
        view.addEventListener("change:resolution", () => { containerFeature.getGeometry().update(); });

        // 
        const QCT_DEFAULT_ZOOM = calculateTargetBaseScale(44, 6.06);
        const t20Feature = new Feature();
        t20Feature.setGeometry(new Point([ahtPosition[0], ahtPosition[1] + 4]));
        const t20Icon = new Icon({ anchor: [0.5, 0.5], src: '/trolley_20FT.png' });
        const t20Style = new Style({ image: t20Icon, scale: QCT_DEFAULT_ZOOM });
        t20Feature.setStyle(t20Style);
        t20Feature.updateScale = () => {
            const currentZommLevel = view.getZoom();
            const scaleRes = QCT_DEFAULT_ZOOM * getScaleFactor(currentZommLevel, MAP_DEFAULT_ZOOM);
            t20Icon.setScale(scaleRes);
            t20Style.setImage(t20Icon);
            t20Feature.setStyle(t20Style);
        };
        t20Feature.updateScale();
        vectorSource.addFeature(t20Feature);
        view.addEventListener("change:resolution", () => { t20Feature.updateScale(); });

    }

    // 岸桥

    console.log(vectorLayer.getSource().getFeatureById("aht-001"));
};